package com.taobao.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.taobao.dao.CommonSerDao;
import com.taobao.dao.RoomTaskDao;
import com.taobao.pojo.ConfirmTime;
import com.taobao.pojo.Equals;
import com.taobao.pojo.HttpContext;
import com.taobao.pojo.State;
import com.taobao.pojo.Task;

public class RoomTaskSerDaoImpl extends CommonSerDao implements RoomTaskDao {

    @SuppressWarnings("unchecked")
    @Override
    public List<Task> getRoomTasks() throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("s", "4");
        params.put("n", "50");
        return (List<Task>) this.postRequest("RoomData", params);
    }

    @Override
    public Object process(HttpContext context) throws Exception {
        Document doc = Jsoup.parse(context.getHtml());
        Elements es = doc.getElementsByTag("tasks");
        List<Task> tasks = new ArrayList<Task>();
        for (Iterator<Element> iterator = es.iterator(); iterator.hasNext();) {
            Element el = (Element) iterator.next();
            Task rt = new Task();

            String tid = el.getElementsByTag("tid").text();
            String fbd = el.getElementsByTag("fbd").text();
            String username = el.getElementsByTag("username").text();
            String itemPrice = el.getElementsByTag("itemPrice").text();
            String priceEqa = el.getElementsByTag("priceEqa").text();
            String ftime = el.getElementsByTag("ftime").text();
            String hpWay = el.getElementsByTag("hpWay").text();
            String status = el.getElementsByTag("status").text();
            try {
                rt.setId(Long.parseLong(tid));
                rt.setPublishPoint(Double.parseDouble(fbd));
                rt.setName(username);
                rt.setPrice(Double.parseDouble(itemPrice));
                rt.setEquals(new Equals(Integer.parseInt(priceEqa)));
                rt.setPublishTime(ftime);
                rt.setConfirmTime(new ConfirmTime(Integer.parseInt(hpWay)));
                rt.setState(new State(Integer.parseInt(status)));
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
            tasks.add(rt);
        }
        
        return tasks;
    }

}
